<?php

/**
 * Radcodes - SocialEngine Module
 *
 * @category   Application_Extensions
 * @package    Badge
 * @copyright  Copyright (c) 2009-2010 Radcodes LLC (http://www.radcodes.com)
 * @license    http://www.radcodes.com/license/
 * @version    $Id$
 * @author     Vincent Van <vincent@radcodes.com>
 */

class Badge_AdminAwardsController extends Core_Controller_Action_Admin {
	
	public function init() {
		
		if (! Engine_Api::_ ()->core ()->hasSubject ()) {
			if (0 !== ($award_id = ( int ) $this->_getParam ( 'award_id' )) && null !== ($award = Engine_Api::_ ()->getItem ( 'badge_award', $award_id ))) {
				Engine_Api::_ ()->core ()->setSubject ( $award );
			}
		}
		
		$this->_helper->requireSubject->setActionRequireTypes ( array ('delete' => 'badge_award', 'edit' => 'badge_award' ) );
	
	}
	
	public function indexAction() {
		$this->view->navigation = $navigation = Engine_Api::_ ()->getApi ( 'menus', 'core' )->getNavigation ( 'badge_admin_main', array (), 'badge_admin_main_awards' );
		
		$this->view->formFilter = $formFilter = new Badge_Form_Admin_Award_Filter ();
		
		// Process form
		$values = array ();
		if ($formFilter->isValid ( $this->_getAllParams () )) {
			$values = $formFilter->getValues ();
		}
		$values = Engine_Api::_ ()->badge ()->filterEmptyParams ( $values );
		
		$this->view->formValues = $values;
		
		$this->view->assign ( $values );
		
		$this->view->paginator = Engine_Api::_ ()->badge ()->getAwardsPaginator ( $values );
		$this->view->paginator->setItemCountPerPage ( 10 );
		$this->view->paginator->setCurrentPageNumber ( $this->_getParam ( 'page', 1 ) );
		$this->view->params = $values;
	
	}
	
	public function addAction() {
		$this->view->form = $form = new Badge_Form_Admin_Award_Add ();
		
		if ($this->getRequest ()->isPost () && $form->isValid ( $this->getRequest ()->getPost () )) {
			$values = $form->getValues ();
			
			$user = Engine_Api::_ ()->user ()->getUser ( $values ['user'] );
			
			$params = array (

			'module' => 'badge', 'controller' => 'awards', 'action' => 'create', 'user' => $user->getIdentity () );
			
			$redirectUrl = $this->getFrontController ()->getRouter ()->assemble ( $params, 'admin_default', true );
			//die($redirectUrl);
			$this->_forward ( 'success', 'utility', 'core', array ('smoothboxClose' => 10, 'parentRedirectTime' => 10, 'parentRedirect' => $redirectUrl, 'messages' => array (Zend_Registry::get ( 'Zend_Translate' )->_ ( 'Redirecting to create form ...' ) ) ) );
		
		}
	
	}
	
	public function createAction() {
		$this->view->navigation = $navigation = Engine_Api::_ ()->getApi ( 'menus', 'core' )->getNavigation ( 'badge_admin_main', array (), 'badge_admin_main_awards' );
		
		$this->view->form = $form = new Badge_Form_Admin_Award_Create ();
		$form->setAction ( $this->getFrontController ()->getRouter ()->assemble ( array ('module' => 'badge', 'controller' => 'awards', 'action' => 'create' ), 'admin_default', true ) );
		
		$viewer = Engine_Api::_ ()->user ()->getViewer ();
		
		if ($this->getRequest ()->isPost ()) {
			$values = $this->getRequest ()->getPost ();
			//var_dump($values['end_settings']);
			if ($values ['end_settings']) {
				$form->end_time->setRequired ( true );
				$form->end_time->setAllowEmpty ( false );
			} else {
				$form->end_time->setIgnore ( true );
				$form->end_time->setRequired ( false );
				$form->end_time->setAllowEmpty ( true );
				
				unset ( $values ['end_time'] );
			}
		} else {
			$badge_id = $this->getRequest ()->getParam ( 'badge_id' );
			if ($badge_id) {
				$form->badge_id->setValue ( $badge_id );
			}
			if ($user_id = $this->getRequest ()->getParam ( 'user_id' )) {
				$form->user_id->setValue ( $user_id );
			}
		}
		
		if ($this->getRequest ()->isPost () && $form->isValid ( $values )) {
			$table = Engine_Api::_ ()->getDbtable ( 'awards', 'badge' );
			
			$db = $table->getDefaultAdapter ();
			$db->beginTransaction ();
			
			try {
				$values = $form->getValues ();
				
				$user = Engine_Api::_ ()->user ()->getUser ( $values ['user_id'] );
				$values ['user_id'] = $user->getIdentity ();
				
				$award = $table->createRow ();
				$award->setFromArray ( $values );
				$award->save ();
				
				// CREATE AUTH STUFF HERE
				$auth = Engine_Api::_ ()->authorization ()->context;
				$roles = array ('owner', 'owner_member', 'owner_member_member', 'owner_network', 'registered', 'everyone' );
				
				$auth_keys = array ('view' => 'everyone', 'comment' => 'registered' );
				
				foreach ( $auth_keys as $auth_key => $auth_default ) {
					$auth_value = isset ( $values ['auth_' . $auth_key] ) ? $values ['auth_' . $auth_key] : $auth_default;
					$authMax = array_search ( $auth_value, $roles );
					
					foreach ( $roles as $i => $role ) {
						$auth->setAllowed ( $award, $role, $auth_key, ($i <= $authMax) );
					}
				}
				
				// Add activity
				$action = Engine_Api::_ ()->getDbtable ( 'actions', 'activity' )->addActivity ( $user, $award, 'badge_award_new' );
				if ($action != null) {
					Engine_Api::_ ()->getDbtable ( 'actions', 'activity' )->attachActivity ( $action, $award );
				}
				
				$notifyApi = Engine_Api::_ ()->getDbtable ( 'notifications', 'activity' );
				$notifyApi->addNotification ( $user, $viewer, $award, 'awarded_badge', array ('label' => $award->getShortType () ) );
				
				$db->commit ();
			} 

			catch ( Exception $e ) {
				$db->rollBack ();
				throw $e;
			}
			
			$this->_helper->redirector->gotoRoute ( array ('action' => 'index' ) );
		}
	
	}
	
	public function editAction() {
		$this->view->navigation = $navigation = Engine_Api::_ ()->getApi ( 'menus', 'core' )->getNavigation ( 'badge_admin_main', array (), 'badge_admin_main_awards' );
		
		$this->view->award = $award = Engine_Api::_ ()->core ()->getSubject ( 'badge_award' );
		
		$this->view->form = $form = new Badge_Form_Admin_Award_Edit ();
		$form->populate ( $award->toArray () );
		
		$auth = Engine_Api::_ ()->authorization ()->context;
		$roles = array ('owner', 'owner_member', 'owner_member_member', 'owner_network', 'registered', 'everyone' );
		$auth_keys = array ('view' => 'everyone', 'comment' => 'registered' );
		
		if (! $this->getRequest ()->isPost ()) {
			foreach ( $auth_keys as $auth_key => $auth_default ) {
				$auth_field = 'auth_' . $auth_key;
				
				foreach ( $roles as $i => $role ) {
					if (isset ( $form->$auth_field->options [$role] ) && 1 === $auth->isAllowed ( $award, $role, $auth_key )) {
						$form->$auth_field->setValue ( $role );
					}
				}
			}
			
			return;
		}
		
		if ($this->getRequest ()->isPost ()) {
			$values = $this->getRequest ()->getPost ();
			//var_dump($values['end_settings']);
			if ($values ['end_settings']) {
				$form->end_time->setRequired ( true );
				$form->end_time->setAllowEmpty ( false );
			} else {
				$form->end_time->setIgnore ( true );
				$form->end_time->setRequired ( false );
				$form->end_time->setAllowEmpty ( true );
				
				unset ( $values ['end_time'] );
			}
		}
		
		if ($this->getRequest ()->isPost () && $form->isValid ( $values )) {
			$table = Engine_Api::_ ()->getDbtable ( 'awards', 'badge' );
			
			$db = $table->getDefaultAdapter ();
			$db->beginTransaction ();
			
			try {
				$values = $form->getValues ();
				
				$user = Engine_Api::_ ()->user ()->getUser ( $values ['user_id'] );
				$values ['user_id'] = $user->getIdentity ();
				
				$award->setFromArray ( $values );
				$award->save ();
				
				// CREATE AUTH STUFF HERE
				foreach ( $auth_keys as $auth_key => $auth_default ) {
					$auth_value = isset ( $values ['auth_' . $auth_key] ) ? $values ['auth_' . $auth_key] : $auth_default;
					$authMax = array_search ( $auth_value, $roles );
					
					foreach ( $roles as $i => $role ) {
						$auth->setAllowed ( $award, $role, $auth_key, ($i <= $authMax) );
					}
				}
				
				$db->commit ();
			} 

			catch ( Exception $e ) {
				$db->rollBack ();
				throw $e;
			}
			
			$savedChangesNotice = Zend_Registry::get ( 'Zend_Translate' )->_ ( "Your changes were saved." );
			$form->addNotice ( $savedChangesNotice );
		
		//$this->_helper->redirector->gotoRoute(array('action' => 'index'));
		}
	
	}
	
	public function deleteAction() {
		
		$this->view->award = $award = Engine_Api::_ ()->core ()->getSubject ( 'badge_award' );
		
		// Check post
		if ($this->getRequest ()->isPost ()) {
			$db = Engine_Db_Table::getDefaultAdapter ();
			$db->beginTransaction ();
			
			try {
				$award->delete ();
				$db->commit ();
				
				Engine_Api::_ ()->core ()->clearSubject ();
			} 

			catch ( Exception $e ) {
				$db->rollBack ();
				throw $e;
			}
			
			$this->_forward ( 'success', 'utility', 'core', array ('smoothboxClose' => 10, 'parentRefresh' => 10, 'messages' => Zend_Registry::get ( 'Zend_Translate' )->_ ( "Award deleted successfully." ) ) );
		}
	}

}